<template>
    <el-dialog v-model="dialogShow" @close="handleClose" style="width: 1400px;" :type="type">
        <template #title>
            <div class="dialog-title">
                <span>日志记录</span>
            </div>
            <div class="date-picker-container">
                <div class="block">
                    <span class="demonstration">执行开始时间：</span>
                    <el-date-picker v-model="startTime" type="datetime" placeholder="选择开始时间"
                        style="width: 200px; margin-left: 10px;" format="YYYY-MM-DD HH:mm:ss" />
                </div>
                <div class="block">
                    <span class="demonstration" style="margin-left: 10px;">执行结束时间：</span>
                    <el-date-picker v-model="endTime" type="datetime" placeholder="选择结束时间"
                        style="width: 200px; margin-left: 10px;" format="YYYY-MM-DD HH:mm:ss" />
                </div>
                <el-button type="primary" @click="handleShow(startTime,endTime)">查询</el-button>
            </div>
        </template>
        <el-table :data="paginatedLogs" style="width: 100%">
            <el-table-column prop="importBy" label="导入人" width="100px"></el-table-column>
            <el-table-column prop="startTime" label="执行开始时间" width="110"></el-table-column>
            <el-table-column prop="endTime" label="执行结束时间" width="110"></el-table-column>
            <el-table-column prop="resultsExecution" label="执行结果">
                <!-- 如果是1 则未成功  如果是0 则为失败 -->
                <template #default="scope">
                    <template v-if="scope.row.resultsExecution === 0">失败</template>
                    <template v-else>成功</template>
                </template>
            </el-table-column>
            <el-table-column prop="numberImports" label="导入数"></el-table-column>
            <el-table-column prop="failNumber" label="失败数"></el-table-column>
            <el-table-column prop="executionLog" label="执行日志" width="320"></el-table-column>
            <el-table-column label="操作" width="210">
                <!-- 源文件 和错误文件的点击下载 都是excle -->
                <template #default="scope">
                    <el-button type="text" @click="handleDownload(scope.row,1)">源文件</el-button>
                    <el-button v-if=" scope.row.failUrl != null" type="text"
                        @click="handleDownload(scope.row, 0)">错误文件</el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage"
            :page-sizes="[10, 20, 50, 100]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper"
            :total="total"></el-pagination>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="hideDialog()">取 消</el-button>
                <el-button type="primary" @click="hideDialog()">确定</el-button>
            </span>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
    import { ref, watch, computed, resolveDirective } from 'vue';
    import { ElDialog, ElInput, ElTable, ElTableColumn, ElButton, ElMessage } from 'element-plus';
    import { post, get } from "@/utils/request";
    const props = defineProps({
        delUrl: String,
        dialogShow: Boolean,
        logData: Array,
        type: {
            default: "0"
        },
    });
    const baseApi = import.meta.env.VITE_BASE_IMG_URL;
    const emit = defineEmits(['close']);
    const searchTime = ref('');
    const startTime = ref('');
    const endTime = ref('');
    const dialogShow = computed({
        get: () => props.dialogShow,
        set: (value) => emit('update:dialogShow', value)
    });
    let flag = ref(false);
    const filteredLogs = computed(() => {
        let logsToFilter=null;
        if (!flag.value) {
             logsToFilter =props.logData
        }else{
             logsToFilter = fetchedLogs.value
        }
        console.log("logsToFilter", logsToFilter);
        if (searchTime.value) {
            return logsToFilter.filter(log => log.time.includes(searchTime.value));
        } else {
            return logsToFilter;
        }
    });

    const handleClose = () => {
        emit('close');
    };
    const handleDownload = (row, fileType) => {
        try {
            const fileName = fileType === '1' || !row.failUrl ? row.importUrl : row.failUrl;
            console.log(fileName);
            const filePath = `${baseApi}/${fileName}`;
            console.log(filePath);
            const link = document.createElement('a');
            link.href = filePath;
            const timestamp = Date.now();
            name = timestamp + "_" + getFileName(fileName);
            link.download = name;
            console.log(link.download)
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        } catch (error) {
            ElMessage.error('下载失败，请稍后再试。');
            console.error(error);
        }
    };

    // 分页
    const currentPage = ref(1);
    const pageSize = ref(10);
    const total = computed(() => filteredLogs.value.length);

    const paginatedLogs = computed(() => {
        const start = (currentPage.value - 1) * pageSize.value;
        const end = start + pageSize.value;
        console.log('11111', filteredLogs.value);
        return filteredLogs.value.slice(start, end);
    });

    const handleSizeChange = (newSize) => {
        pageSize.value = newSize;
        // 重置当前页码为1
        currentPage.value = 1;
    };

    const handleCurrentChange = (newPage) => {
        currentPage.value = newPage;
    };

    function hideDialog() {
        dialogShow.value = false
    }
    const fetchedLogs = ref([]);
    const handleShow = (startTime, endTime) => {
        console.log(startTime, endTime);
        const params = {
            startTime,
            endTime,
            type: props.type
        };
        get('/wineJar/import/log', params).then(res => {
            console.log('res', res);
            // 创建一个新的变量来存储查询结果
            fetchedLogs.value = res;
            flag.value = true
            console.log('fetchedLogs', fetchedLogs.value);

        })
    };


    // 写一个名字截取的方法
    const getFileName = (filePath) => {
        console.log(filePath);
        const lastSlashIndex = filePath.lastIndexOf('/');
        filePath = filePath.substring(lastSlashIndex + 1);
        return filePath;
    }


</script>

<style scoped>
    .dialog-title {
        display: flex;
        align-items: center;
        /* 下间距 */
        margin-bottom: 10px;
    }

    .date-picker-container {
        display: flex;
        /* justify-content: space-between; */
        margin-bottom: 10px;
        /* 上间距 */
        margin-top: 10px;
        /* 左间距 */
        margin-left: 0px;
    }

    /* 添加一些样式以确保分页组件与表格对齐 */
    .el-pagination {
        margin-top: 20px;
        text-align: center;
    }
</style>